﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using core;
using shop;

namespace comix
{
    public class LCustomer:SiteItemSingleIUD
    {
        public Address address;
        public string username;
        public string password;
        public string firstname;
        public string lastname;
        public string usercode;
        public int special;
        public bool notifications;
        public bool newsletters;
        public DateTime registrationdate;
        public DateTime lastlogindate;
        public int nlogins;
        public int specialtype;

        private DeviceCollection _userdevices;
        public DeviceCollection Userdevices
        {
            get
            {
                if (_userdevices == null)
                {
                    _userdevices = new DeviceCollection();
                    _userdevices.Command.CommandText = "SELECT * FROM USERDEVICES WHERE usr_id = @usr_id";
                    _userdevices.Command.Parameters.Add(new SqlParameter("@usr_id", Id));
                    _userdevices.FillItem();
                }
                return _userdevices;
            }
        }

        private UserBookCollection _userBooks;
        public UserBookCollection UserBooks
        {
            get
            {
                if (_userBooks == null)
                {
                    _userBooks = new UserBookCollection();
                    _userBooks.Command.CommandText = "SELECT * FROM BOOKS2USERS WHERE u2b_usr_id = @usr_id";
                    _userBooks.Command.Parameters.Add(new SqlParameter("@usr_id", Id));
                }
                return _userBooks;
            }
        }

        public LCustomer()
        {
            address = new Address();
            InsertCommand.CommandText = "CustomerInsert";
            InsertCommand.CommandType = System.Data.CommandType.StoredProcedure;
            m_updatecommand.CommandText = "CustomerUpdate";
            m_updatecommand.CommandType = System.Data.CommandType.StoredProcedure;
            Command.CommandText = "CustomerSelect";
            Command.CommandType = System.Data.CommandType.StoredProcedure;
        }



        public bool Register(string _username, string _password, string _deviceid, string _firstname, string _lastname, bool _notifyok, bool _newslettersok, string _address, string _city, string _tk, string _phone, int _country)
        {
            bool r = true;
            try
            {
                SetFields(_username, _password, _firstname, _lastname, _notifyok, _newslettersok, _address, _city, _tk, _phone, _country);
                if (isDummy())
                {
                    if (isDummyExistingUser())
                    {
                        LogIn();
                        Fill();
                    }
                    else
                    {
                        r = DoInsertNewUser(_deviceid);
                    }
                }
                else
                {
                    if (_deviceid != "")
                    {
                        int oldid = wasDummyUser(_deviceid);
                        if (oldid > 0)
                        {
                            Id = oldid;
                            Fill();
                            username = _username;
                            password = _password;
                            r = Update();
                            return true;
                        }
                    }
                    if (UserNameExists(username))
                    {
                        r = false;
                        m_lasterror = "To mail αυτό χρησιμοποιήται ήδη";
                        LogOff();
                    }
                    else
                    {
                        r = DoInsertNewUser(_deviceid);
                    }
                }
            }
            catch (Exception e)
            {
                r = false;
                m_lasterror = e.Message;
            }
            return r;
        }

        private bool DoInsertNewUser(string device)
        {
            CreateUserCode();
            bool r = Insert();
            if (r && device.Length>0)
            {
                Device d = new Device();
                d.usrid = Id;
                d.device = device;
                d.SetIsNew();
                Userdevices.Items.Add(d);
                Userdevices.Save();
            }
            return r;
        }

        public bool Change(string _username, string _password, string _firstname, string _lastname, bool _notifyok, bool _newslettersok, string _address, string _city, string _tk, string _phone, int _country)
        {
            bool r = true;
            try
            {
                if (_username != username)
                {
                    if (UserNameExists(_username))
                    {
                        m_lasterror = "Το mail αυτό χρησιμοποιείται ήδη";
                        r = false;
                        return r;
                    }
                }
                SetFields(_username, _password, _firstname, _lastname, _notifyok, _newslettersok, _address, _city, _tk, _phone, _country);
                r = Update();
            }
            catch(Exception e)
            {
                r = false;
                m_lasterror = e.Message;
            }
            return r;
        }

        private void CreateUserCode()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            Random r = new Random();
            for (int i = 0; i < 32; i++)
            {
                char k = (char)(r.Next(90) + 34);

                sb.Append(k);
            }
            usercode = sb.ToString();
        }

        public bool LogIn()
        {
            SqlCommand com = new SqlCommand();
            com.CommandText = "SELECT usr_id FROM USERS WHERE usr_username = @usr_username AND usr_password = @usr_password";
            com.Parameters.Add(new SqlParameter("@usr_username", username));
            com.Parameters.Add(new SqlParameter("@usr_password", password));
            object o = ExecuteScalar(com);
            if (o == null)
            {
                LogOff();
                return false;
            }
            else
                m_id = Convert.ToInt32(o);
            return true;
        }

        public void LogOff()
        {
            SetFields("", "", "", "", false, false, "", "", "", "", 0);
            Id = 0;
        }

        private void SetFields(string _username, string _password, string _firstname, string _lastname, bool _notifyok, bool _newslettersok, string _address, string _city, string _tk, string _phone, int _country)
        {
            username = _username;
            password = _password;
            firstname = _firstname;
            lastname = _lastname;
            notifications = _notifyok;
            newsletters = _newslettersok;
            address.Set(_address, _city, _tk, _phone, "", _country);
        }

        private bool UserNameExists(string username)
        {
            SqlCommand com = new SqlCommand();
            com.CommandText = "SELECT COUNT(*) FROM USERS WHERE usr_username = @usr_name";
            com.Parameters.Add(new SqlParameter("@usr_name", username));
            int n = Convert.ToInt32(ExecuteScalar(com));
            return (n > 0);
        }

        public bool isDummy()
        {
            return (password == "");
        }

        public bool isDummyExistingUser()
        {
            SqlCommand com = new SqlCommand();
            com.CommandText = "SELECT COUNT(*) FROM USERS WHERE usr_username = @usr_name AND usr_password = ''";
            com.Parameters.Add(new SqlParameter("@usr_name", username));
            int n = Convert.ToInt32(ExecuteScalar(com));
            return (n > 0);
        }

        public int wasDummyUser(string devid)
        {
            SqlCommand com = new SqlCommand();
            com.CommandText = "SELECT usr_id FROM USERS WHERE usr_username = @usr_device AND usr_password = ''";
            com.Parameters.Add(new SqlParameter("@usr_device", devid));
            object o = com.ExecuteScalar();
            if (o == null)
                return 0;
            else
                return Convert.ToInt32(o);  
        }

        public override void SetInsertParameters()
        {
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_firstname", firstname));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_lastname", lastname));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_username", username));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_password", password));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_code", usercode));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_notifications", notifications));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_newsletterok", newsletters));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_address", address.Odos));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_city", address.City));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_tk", address.TK));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_phone", address.Phone));
            m_insertcommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_plc_id", address.CountryId));
        }

        public override void SetUpdateParameters()
        {
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_firstname", firstname));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_lastname", lastname));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_username", username));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_password", password));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_notifications", notifications));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_newsletterok", newsletters));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_address", address.Odos));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_city", address.City));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_tk", address.TK));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_phone", address.Phone));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@adr_plc_id", address.CountryId));
            m_updatecommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_id", Id));
        }

        public override void DoFill(System.Data.SqlClient.SqlDataReader rdr)
        {           
            m_id = (int)rdr["usr_id"];
            
            firstname = SafeString("usr_firstname",rdr);
            lastname = SafeString("usr_lastname",rdr);
            username = SafeString("usr_username",rdr);
            password = SafeString("usr_password",rdr);
            newsletters = rdr.IsDBNull(rdr.GetOrdinal("usr_newsletterok")) ? false : (bool)rdr["usr_newsletterok"];
            notifications = (bool)rdr["usr_notifications"];
            registrationdate = (DateTime)rdr["usr_registrationdate"];
            lastlogindate = (DateTime)rdr["usr_lastlogin"];
            specialtype = (int)rdr["usr_special"];
            usercode = (string)rdr["usr_code"];
            nlogins = SafeInt("usr_nlogins", rdr);
            address.DoFill(rdr);
            address.Id = SafeInt("usr_adr_id", rdr);
         }




        public override void SetDeleteParameters()
        {
           
        }

        public override void SetSelectParameters()
        {
            m_com.Parameters.Add(new System.Data.SqlClient.SqlParameter("@usr_id", Id));
        }
    }
}
